//
//  AppDelegate.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/5.
//

import UIKit
import KeychainAccess
import SwiftyStoreKit
import Reachability
import CommonCrypto

@main
class AppDelegate: UIResponder, UIApplicationDelegate, BUSplashAdDelegate, WXApiDelegate {

    var window: UIWindow?
    
    var splashAd: BUSplashAd?
    var isShowAding = false
    var reachability: Reachability?

    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        if #available(iOS 13.0, *) {
            window?.overrideUserInterfaceStyle = .light
        }

        // 清除每天的使用次数
        let time = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyzPreUseTime) as? String ?? ""
        let ctime = Date().description.components(separatedBy: " ").first
        if ctime != time {
            UserDefaults.standard.set(0, forKey: UserDefaultsKey.picxyzUseCount)
        }
        UserDefaults.standard.set(ctime, forKey: UserDefaultsKey.picxyzPreUseTime)
        UserDefaults.standard.synchronize()

        reachability = try! Reachability()
        // 检测网络连接状态
        reachability?.whenReachable = { [weak self] res in
            UserDefaults.standard.set(1, forKey: UserDefaultsKey.haveNetwork)
            UserDefaults.standard.synchronize()
            self?.requestLaunch()
            self?.setupBUAdSDK()
        }
        try? reachability!.startNotifier()
        
        goToNextStep()
        
        return true
    }
    
    func goToNextStep(){
        let tabVc = WMBaseTabBarController()
        self.window?.rootViewController = tabVc
        window?.makeKeyAndVisible()
        window?.rootViewController?.view.addSubview(launchView)

        UMConfigure.initWithAppkey("68da7f728560e34872bc69eb", channel: "App Store")
        
        NTESQuickLoginManager.sharedInstance().register(withBusinessID: "b7079d2922d04ac4aeec2ef28ca3347c")
        NTESQuickLoginManager.sharedInstance().getPhoneNumberCompletion { resultDic in
            let resultCode = resultDic["resultCode"] as? String ?? ""
            let token = resultDic["token"] as? String ?? ""
            UserDefaults.standard.setValue(token, forKey: UserDefaultsKey.oneKeyPhoneTokenKey)
            UserDefaults.standard.setValue(resultCode, forKey: UserDefaultsKey.oneKeyPhoneCodeKey)
            UserDefaults.standard.synchronize()
        }

        WXApi.registerApp("wx93fd35fe0dd46afb", universalLink: "https://dkqsyapi.awaketec.com/dkqsy/")
//        WXApi.checkUniversalLinkReady { step, result in
//            print("step====>\(step)--->\(result)")
//        }
        
        let isFirstIn = UserDefaults.standard.value(forKey: UserDefaultsKey.isFirstIn) as? Int ?? 0
        if isFirstIn != 0 {
            setupBUAdSDK()
        }
        checkPurchase()

        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
            self?.requestLaunch()
        }
    }


    func requestLaunch() {
        let params: [String: Any] = [
            "udid": getUUID(),
            "channel": "app_store",
            "sysOs": "iOS",
            "productVersion": AppInfo.appVersion,
            "sysVersion": AppInfo.iOSVersion,
            "deviceBrand": "APPLE",
            "deviceModel": AppInfo.deviceModel,
            "androidid": "",
            "imei": "",
            "mac": "",
            "idfa": getUUID(),
            "umengPid": "",
            "oaid": "",
            "efrom": AppInfo.bundleIdentifier,
        ]
        WMAgentApi.shared.requestApi(.startUp(params)) { res in
            if let data = res["data"] as? [String: Any], let dict = data["dataDictionary"] as? [String: Any] {
                UserDefaults.standard.setValue("\(data["startIcon"] ?? 0)", forKey: UserDefaultsKey.startIcon)
                UserDefaults.standard.setValue(dict["showad"], forKey: UserDefaultsKey.showad)
                UserDefaults.standard.setValue(dict["userAgree"], forKey: UserDefaultsKey.userProtocol)
                UserDefaults.standard.setValue(dict["privateAgree"], forKey: UserDefaultsKey.sercurityProtocol)
                UserDefaults.standard.setValue(dict["paymentAgree"], forKey: UserDefaultsKey.paymentAgree)
                UserDefaults.standard.setValue(dict["autoAgree"], forKey: UserDefaultsKey.autoAgree)
                // 分享
                UserDefaults.standard.setValue(dict["shareTitle"], forKey: UserDefaultsKey.shareTitle)
                UserDefaults.standard.setValue(dict["shareContent"], forKey: UserDefaultsKey.shareContent)
                UserDefaults.standard.setValue(dict["shareUrl"], forKey: UserDefaultsKey.shareUrl)
                UserDefaults.standard.setValue(dict["ssys"] ?? 0, forKey: UserDefaultsKey.ssysUrl)
                UserDefaults.standard.setValue(dict["help"] ?? 0, forKey: UserDefaultsKey.helpUrl)
                UserDefaults.standard.setValue(dict["picxyz"] ?? 0, forKey: UserDefaultsKey.picxyz)
                UserDefaults.standard.setValue(dict["picfree"] ?? 0, forKey: UserDefaultsKey.picfree)
                UserDefaults.standard.setValue(dict["picslimit"] ?? 0, forKey: UserDefaultsKey.picslimit)
                UserDefaults.standard.setValue(dict["picsdesc"] ?? "", forKey: UserDefaultsKey.picsdesc)
                UserDefaults.standard.setValue(dict["videojc"] ?? "", forKey: UserDefaultsKey.videojc)

                UserDefaults.standard.synchronize()
                NotificationCenter.default.post(.networkStatusChanged)

                // 使用示例
                let cipherText = dict["picxyz"] ?? ""
                let key = "87654321!@#$%^&*"
                if let plainText = self.decryptAESECB(cipherText: cipherText as! String, key: key) {
                    print("明文: \(plainText)")
                    UserDefaults.standard.setValue(plainText, forKey: UserDefaultsKey.picxyz)
                } else {
                    print("解密失败")
                }
            }
        }
        requestEventSave(title: "启动", mode: "启动")
    }
    
    func decryptAESECB(cipherText: String, key: String) -> String? {
        // 1. Base64 decode cipher text
        guard let cipherData = Data(base64Encoded: cipherText) else {
            print("Base64 decoding failed")
            return nil
        }
        
        // 2. Prepare key (UTF-8 encoded)
        guard let keyData = key.data(using: .utf8) else {
            print("Key encoding failed")
            return nil
        }
        
        // 3. Create output buffer
        var decryptedLength = 0
        var outputBuffer = [UInt8](repeating: 0, count: cipherData.count)
        
        // 4. Get pointers to the data without nested closures
        let cipherBytes = [UInt8](cipherData)
        let keyBytes = [UInt8](keyData)
        
        // 5. Perform decryption
        let status = CCCrypt(
            CCOperation(kCCDecrypt),
            CCAlgorithm(kCCAlgorithmAES),
            CCOptions(kCCOptionPKCS7Padding | kCCOptionECBMode),
            keyBytes,
            keyData.count,
            nil,
            cipherBytes,
            cipherData.count,
            &outputBuffer,
            outputBuffer.count,
            &decryptedLength
        )
        
        // 6. Check if decryption was successful
        guard status == kCCSuccess else {
            print("Decryption failed, status code: \(status)")
            return nil
        }
        
        // 7. Extract decrypted data and convert to string
        let resultData = Data(outputBuffer[0..<decryptedLength])
        return String(data: resultData, encoding: .utf8)
    }

    func checkPurchase() {
        SwiftyStoreKit.completeTransactions() { (purchases) in
            for purchase in purchases.reversed() {
                switch purchase.transaction.transactionState {
                case .purchased,.restored:
                    print("已完成订单")
                    return
                case .failed,.purchasing,.deferred:
                    break
                default:
                    break
                }
            }
            
        }
    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        return WXApi.handleOpenUniversalLink(userActivity, delegate: self)
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        if url.host == "oauth" || url.host == "resendContextReqByScheme" {
            return WXApi.handleOpen(url, delegate: self)
        }
        
        return true
    }
    
    //APP给微信发送消息，微信返回APP回调
    func onResp(_ resp: BaseResp) {
        if resp.isKind(of: SendAuthResp.self) {
            //微信授权登录的回调处理
            if resp.errCode==0 {
                if resp is SendAuthResp {
                    if (resp as! SendAuthResp).state == "wx_oauth_authorization_state" {
                        let code = (resp as! SendAuthResp).code
                        NotificationCenter.default.post(name: NSNotification.Name("WeChatLoginResponse"), object: resp, userInfo: ["code":code!, "state":(resp as! SendAuthResp).state!])
                    }
                }
            } else {
                print("授权失败")
            }
        }
    }

    func setupBUAdSDK() {
        let configuration = BUAdSDKConfiguration()
        configuration.appID = "5737629"
        configuration.appLogoImage = UIImage(named: "app_icon")
        BUAdSDKManager.start(asyncCompletionHandler: { [weak self] (success, error) in
            if success {
                initAdSuccess = true
                NotificationCenter.default.post(.adInitSuccessed)
                DispatchQueue.main.async { [weak self] in
                    self?.addSplashAD()
                }
            }else {
                self?.launchView.removeFromSuperview()
            }
        })
    }
    
    func addSplashAD() {
        let isFirstIn = UserDefaults.standard.value(forKey: UserDefaultsKey.isFirstIn) as? Int ?? 0
        UserDefaults.standard.setValue(1, forKey: UserDefaultsKey.isFirstIn)
        UserDefaults.standard.synchronize()
        if isFirstIn == 0 {
            launchView.removeFromSuperview()
            return
        }
        let isMember = UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0
        if isMember == 1 {
            launchView.removeFromSuperview()
            return
        }
        if UIDevice.current.userInterfaceIdiom == .pad {
            launchView.removeFromSuperview()
            return
        }

        splashAd = BUSplashAd(slotID: "892772633", adSize: UIScreen.main.bounds.size)
        splashAd!.supportCardView = true
        splashAd!.supportZoomOutView = true
        
        splashAd!.delegate = self
        splashAd!.tolerateTimeout = 3
        
        splashAd!.loadData()
        
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
            try AVAudioSession.sharedInstance().setActive(true)
            UIApplication.shared.beginReceivingRemoteControlEvents()
            self.becomeFirstResponder()
        } catch {
            print("Failed to set audio session: \(error)")
        }
    }

    func splashAdLoadSuccess(_ splashAd: BUSplashAd) {
        Async.main(after: 1) { [weak self] in
            self?.launchView.removeFromSuperview()
        }
        splashAd.showSplashView(inRootViewController: window!.rootViewController!)
    }
    
    func splashAdLoadFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        Async.main(after: 1) { [weak self] in
            self?.launchView.removeFromSuperview()
        }
    }
    
    func splashAdRenderSuccess(_ splashAd: BUSplashAd) {
        
    }
    
    func splashAdRenderFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        Async.main(after: 1) { [weak self] in
            self?.launchView.removeFromSuperview()
        }
    }
    
    func splashAdWillShow(_ splashAd: BUSplashAd) {
        
    }
    
    func splashAdDidShow(_ splashAd: BUSplashAd) {
        
    }
    
    func splashAdDidClick(_ splashAd: BUSplashAd) {
        Async.main(after: 1) { [weak self] in
            self?.launchView.removeFromSuperview()
        }
    }
    
    func splashAdDidClose(_ splashAd: BUSplashAd, closeType: BUSplashAdCloseType) {
        
    }
    
    func splashAdViewControllerDidClose(_ splashAd: BUSplashAd) {
        Async.main(after: 1) { [weak self] in
            self?.launchView.removeFromSuperview()
        }
    }
    
    func splashDidCloseOtherController(_ splashAd: BUSplashAd, interactionType: BUInteractionType) {
        Async.main(after: 1) { [weak self] in
            self?.launchView.removeFromSuperview()
        }
    }
    
    func splashVideoAdDidPlayFinish(_ splashAd: BUSplashAd, didFailWithError error: (any Error)?) {
        Async.main(after: 1) { [weak self] in
            self?.launchView.removeFromSuperview()
        }
    }
    
    lazy var launchView: UIView = {
        let view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = .white
        
        let iv = UIImageView()
        iv.image = UIImage(named: "app_icon")
        view.addSubview(iv)
        iv.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.height.equalTo(80)
            make.bottom.equalTo(-120)
        }
        
        return view
    }()

}

var topViewController: UIViewController? {
    var topViewController = UIApplication.shared.delegate?.window??.rootViewController

    if let viewController = topViewController as? UITabBarController {
        topViewController = viewController.selectedViewController
    }

    if let viewController = topViewController as? UINavigationController {
        topViewController = viewController.visibleViewController
    }
    return topViewController
}

func requestEventSave(title: String, mode: String) {
    let params: [String: Any] = [
        "udid": getUUID(),
        "userId": UserDefaults.standard.value(forKey: UserDefaultsKey.loginUserId) as? Int ?? 0,
        "phone": UserDefaults.standard.value(forKey: UserDefaultsKey.loginPhone) as? String ?? "",
        "efrom": "funcs",
        "etype": "click",
        "title": title,
        "mode": mode,
        "channel": "app_store",
        "systemName": "iOS",
        "productVersion": AppInfo.appVersion,
        "sysVersion": AppInfo.iOSVersion,
        "deviceBrand": "APPLE",
        "deviceModel": AppInfo.deviceModel,
        "androidid": "",
        "imei": "",
        "mac": "",
        "idfa": getUUID(),
        "umengPid": "",
        "oaid": "",
    ]
    WMAgentApi.shared.requestRaw(.eventSave(params)) { _ in }
}


func getUUID() -> String{
    let uuidKey: String = "WM_UUID_KEY"
    let keychain = Keychain(service: AppInfo.bundleIdentifier)
    var uuid:String = ""
    do {
        uuid = try keychain.get(uuidKey) ?? ""
    }
    catch let error {
        print(error)
    }
    if uuid.isEmpty {
        uuid = UUID().uuidString
        do {
            try keychain.set(uuid, key: uuidKey)
        }
        catch let error {
            print(error)
            uuid = ""
        }
    }
    return uuid
}
